package io.github.xbeeant.eoffice.service.impl;

import io.github.xbeeant.core.IdWorker;
import io.github.xbeeant.eoffice.antdesign.TreeNode;
import io.github.xbeeant.eoffice.config.AbstractSecurityMybatisPageHelperServiceImpl;
import io.github.xbeeant.eoffice.mapper.FolderMapper;
import io.github.xbeeant.eoffice.model.Folder;
import io.github.xbeeant.eoffice.service.IFolderService;
import io.github.xbeeant.spring.mybatis.pagehelper.IMybatisPageHelperDao;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * eoffice_folder
 */
@Service
public class FolderServiceImpl extends AbstractSecurityMybatisPageHelperServiceImpl<Folder, Long> implements IFolderService {

    @Autowired
    private FolderMapper folderMapper;

    @Override
    public IMybatisPageHelperDao<Folder, Long> getRepositoryDao() {
        return this.folderMapper;
    }

    @Override
    public void setDefaults(Folder record) {
        if (record.getFid() == null) {
            record.setFid(IdWorker.getId());
        }
    }

    @Override
    public List<TreeNode> childNodes(String userId) {
        List<Folder> list = folderMapper.userFolder(userId);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<TreeNode> treeNodes = new ArrayList<>();
        TreeNode treeNode;
        for (Folder folder : list) {
            treeNode = new TreeNode();
            treeNode.setpKey(folder.getPfid());
            treeNode.setKey(folder.getFid());
            treeNode.setTitle(folder.getFname());
            treeNode.setCode(folder.getType());
            treeNodes.add(treeNode);
        }
        for (TreeNode node : treeNodes) {
            for (TreeNode subNode : treeNodes) {
                if (subNode.getpKey().equals(node.getKey())) {
                    subNode.setParentExist(true);
                    node.addChildren(subNode);
                }
            }
        }

        treeNodes.removeIf(node -> node.getpKey() != 0);
        return treeNodes;
    }
}
